<template>
	<view class="u-wrap">
		<!-- 最上面的教室选择 -->
		<u-tabs   style="height: 80rpx;" :current="current1" :list="xiaoqu" 
			scroll-y="true" lineWidth="50" lineColor="blue"
			:activeStyle="{ color: 'black',  transform: 'scale(1)'}"
			:inactiveStyle="{color: '#606266',transform: 'scale(0.9)'}"
			itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" @change="change">
		</u-tabs>
		<!-- 搜索框 -->
		<view style="display:flex;width: 700rpx ;background-color:#F2F2F2;align-items: center;justify-content: center;margin: 10rpx auto;border-radius:20rpx;">
			<u-search margin="0 30rpx 0 0" placeholder="请输入商品名称"   actionText="搜索" v-model="sousuokey" @search="usersearch" @custom="usersearch" ></u-search>
		</view>
		
		<view class="u-menu-wrap">
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop"
			 :scroll-into-view="itemId">
				<view v-for="(item,index) in shangpin_lists" :key="index" class="u-tab-item" :class="[current == index ? 'u-tab-item-active' : '']"
				 @tap.stop="swichMenu(index)">
					<text class="u-line-1">{{item.name}}</text>
				</view>
			</scroll-view>
			<scroll-view :scroll-top="scrollRightTop" scroll-y scroll-with-animation class="right-box" @scroll="rightScroll">
				<view class="page-view">
					<view class="class-item" :id="'item' + index" v-for="(item , index) in shangpin_lists" :key="index">
						<view class="item-title">
							<text>{{item.name}}</text>
						</view>
						<view class="item-container">
							<view @click="xiaoshou_show(item1)" class="thumb-box" v-for="(item1, index1) in item._id" :key="index1">
								<view style="display: flex;align-items: center;">
									<image class="item-menu-image" :src="item1.zhaopian" mode=""></image>
									<view style="margin-left: 25rpx;">
										<view class="item-menu-name">{{item1.name}}</view>
										<view style="display: flex;color: darkgrey;font-size:28rpx; ">库存:{{item1.kucunliang}}</view>
									</view>
								</view>
								<view class="">
									{{item1.jiage}}元
								</view>
								
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		
		<!-- 下面是添加新商品时出现的弹窗 -->
		<model v-if='show1' @colseModel='show1 = false'>
				<view style="display: flex;background-color:blue;color: white;border-radius: 20rpx;padding: 15rpx ; margin: 25rpx auto;justify-content: center;">
					给【{{shu11}}】添加商品信息！
				</view>
				<view style="display: flex;margin-bottom: 10rpx;">输入商品名称</view>
				<uni-easyinput type="text" v-model="shu17" />
				<view style="display: flex;margin-bottom: 10rpx;margin-top: 30rpx;">输入商品介绍</view>
						<uni-easyinput type="text" v-model="shu2" /> 
				<view style="display: flex;margin-bottom: 10rpx;margin-top: 30rpx;">输入库存数量</view>
						<uni-easyinput type="number" v-model="shu3" /> 
				<view style="display: flex;margin-bottom: 10rpx;margin-top: 30rpx;">输入商品价格</view>
						<uni-easyinput type="number" v-model="shu4" /> 
				<uni-file-picker style="margin: 30rpx;" limit="1" :del-icon="false"  :imageStyles="imageStyles"
					file-mediatype="image" @success="fanhuiurl">照片上传</uni-file-picker>
				<view style="display: flex;width: 60%;justify-content: space-around;margin: 30rpx auto;color: white;">
					<view style="display: flex;background-color: blue;border-radius: 15rpx;padding: 20rpx 60rpx;" @click="show1 = false">取消</view>
					<view style="display: flex;background-color: blue;border-radius: 15rpx;padding: 20rpx 60rpx;" @click="xinshangpin()">确定</view>
				</view>
		</model>
		<!-- 下面是卖货时出现的弹窗 -->
		<model v-if='show2' @colseModel='show2 = false'>
				<view style="display: flex;background-color:blue;color: white;border-radius: 20rpx;padding: 15rpx ; margin: 25rpx auto;justify-content: center;">
					添加销售信息！
				</view>
				<view style="display: flex;margin-bottom: 10rpx;">商品名称</view>
				<uni-easyinput type="text" v-model="shu10" disabled="" />
				<view style="display: flex;margin-bottom: 10rpx;">购买人</view>
				<uni-easyinput type="text" v-model="shu9" />
				<view style="display: flex;margin-bottom: 10rpx;margin-top: 30rpx;">购买数量</view>
						<uni-easyinput type="number" v-model="shu6" /> 
				<view style="display: flex;margin-bottom: 10rpx;margin-top: 30rpx;">购买价格</view>
						<uni-easyinput type="number" v-model="shu7" /> 
				<view style="display: flex;margin-bottom: 10rpx;margin-top: 30rpx;">备注</view>
						<uni-easyinput type="text" v-model="shu8" /> 
				<view style="display: flex;width: 60%;justify-content: space-around;margin: 30rpx auto;color: white;">
					<view style="display: flex;background-color: blue;border-radius: 15rpx;padding: 20rpx 60rpx;" @click="show2 = false">取消</view>
					<view style="display: flex;background-color: blue;border-radius: 15rpx;padding: 20rpx 60rpx;" @click="xiaoshou()">确定</view>
				</view>
		</model>
	</view>
</template>

<script>
	import getDateTime from '@/common/getdateTime.js'; 
	import model from '../../components/model.vue'
	export default {
		components: {
			model
		},
		data() {
			return {
				scrollTop: 0, //tab标题的滚动条位置
				oldScrollTop: 0,
				current: 0, // 预设当前项的值
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				itemId: '', // 栏目右边scroll-view用于滚动的id
				shangpin_lists: [],
				menuItemPos: [],
				arr: [],
				scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
				timer: null, // 定时器
				sousuokey:'',//搜索值初始值为空
				shangpinlist:[],//商品列表
				maihuomingxi:[],//本校区的卖货明细
				xiaoqu:[],//校区信息数组
				current1:0,//UTAB的标签数字
				meiyi_userinfo:[],
				imageStyles: {
					width: 100,
					height: 100,
					border: {
					color:"blue",
					width:2,
					style:'dashed',
					radius:'12px'
					}
				},
				show:false,//校区选择是否显示
				show1:false,//添加商品时出现的弹窗
				show2:false,//卖货时出现的弹窗
				show3:false,//商品的删除是否显示
				shu17:'',//商品名称
				shu2:'',//商品介绍
				shu3:'',//库存数量
				shu4:'',//输入商品价格
				shu5:'',//照片地址
				shu9:'',//购买人
				shu6:1,//购买数量
				shu7:'',//购买价格
				shu8:'',//备注
				shu10:'',//商品名称
				shu11:'',//校区名称
				shu12:false,//删除
				shu13:'删除商品',
				shu14:'',//填加销售信息时的校区
				shu15:'',//销售产品时，产品的ID
				shu16:'',//销售产品时，产品的库存时
			}
		},
		onReady() {
			this.getMenuItemTop()
		},
		async onLoad() {
			let meiyi_name_tel=await uni.getStorageSync('meiyi_name_tel')
			this.jingshouren=meiyi_name_tel.name+meiyi_name_tel.mobile
			this.xiaoqufun()
		},
		onNavigationBarButtonTap() {
			uni.navigateTo({
				url: '/pages/xiaoshou_lists/xiaoshou_lists?xiaoqu='+encodeURIComponent(JSON.stringify(this.shu1)),
			});
		},
		methods: {
			// 点击左边的栏目切换
			async swichMenu(index) {
				if(this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if (index == this.current) return;
				this.scrollRightTop = this.oldScrollTop;
				this.$nextTick(function(){
					this.scrollRightTop = this.arr[index];
					this.current = index;
					this.leftMenuStatus(index);
				})
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.' + elClass).fields({
						size: true
					}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if (!res) {
							setTimeout(() => {
								this.getElRect(elClass);
							}, 10);
							return;
						}
						this[dataVal] = res.height;
						resolve();
					}).exec();
				})
			},
			// 观测元素相交状态
			async observer() {
				this.shangpin_lists.map((val, index) => {
					let observer = uni.createIntersectionObserver(this);
					// 检测右边scroll-view的id为itemxx的元素与right-box的相交状态
					// 如果跟.right-box底部相交，就动态设置左边栏目的活动状态
					observer.relativeTo('.right-box', {
						top: 0
					}).observe('#item' + index, res => {
						if (res.intersectionRatio > 0) {
							let id = res.id.substring(4);
							this.leftMenuStatus(id);
						}
					})
				})
			},
			// 设置左边菜单的滚动状态
			async leftMenuStatus(index) {
				this.current = index;
				// 如果为0，意味着尚未初始化
				if (this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
					await this.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 将菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2;
			},
			// 获取右边菜单每个item到顶部的距离
			getMenuItemTop() {
				new Promise(resolve => {
					let selectorQuery = uni.createSelectorQuery();
					selectorQuery.selectAll('.class-item').boundingClientRect((rects) => {
						// 如果节点尚未生成，rects值为[](因为用selectAll，所以返回的是数组)，循环调用执行
						if(!rects.length) {
							setTimeout(() => {
								this.getMenuItemTop();
							}, 10);
							return ;
						}
						rects.forEach((rect) => {
							// 这里减去rects[0].top，是因为第一项顶部可能不是贴到导航栏(比如有个搜索框的情况)
							this.arr.push(rect.top - rects[0].top);
							resolve();
						})
					}).exec()
				})
			},
			// 右边菜单滚动
			async rightScroll(e) {
				this.oldScrollTop = e.detail.scrollTop;
				if(this.arr.length == 0) {
					await this.getMenuItemTop();
				}
				if(this.timer) return ;
				if(!this.menuHeight) {
					await this.getElRect('menu-scroll-view', 'menuHeight');
				}
				setTimeout(() => { // 节流
					this.timer = null;
					// scrollHeight为右边菜单垂直中点位置
					let scrollHeight = e.detail.scrollTop + this.menuHeight / 2;
					for (let i = 0; i < this.arr.length; i++) {
						let height1 = this.arr[i];
						let height2 = this.arr[i + 1];
						// 如果不存在height2，意味着数据循环已经到了最后一个，设置左边菜单为最后一项即可
						if (!height2 || scrollHeight >= height1 && scrollHeight < height2) {
							this.leftMenuStatus(i);
							return ;
						}
					}
				}, 10)
			},
			//点搜索时运行
			usersearch(){
				this.shangpinlistfun()
			},
			// 获取商品
			shangpinlistfun(){
				uni.showLoading({
					title: '商品获取…',
					mask: true
				});
				uniCloud.callFunction({
					name:"delpic",
					data:{
						leixing:9,//
						xiaoqu:this.shu1,
						key:this.sousuokey
					}
				}).then(res=>{
					this.shangpin_lists=res.result.res.data
					uni.hideLoading()
				})
			},
			
			// 下面是删除操作，一、shangpin中删除记录,二、xiugaishuju中添加一条删除记录
			shanchu(e){
				console.log(e)
				return
				uni.showModal({
					title: '重要提示',
					content: '再次确认，一定要删除吗？再次确认，一定要删除吗？再次确认，一定要删除吗？再次确认，一定要删除吗？再次确认，一定要删除吗？再次确认，一定要删除吗？',
					showCancel: true,
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						uni.showLoading({
							title: '删除中…',
							mask: true
						});
						uniCloud.callFunction({
							name:"funshare",
							data:{
								leixing:32,//类型为16时，新增卖货明细
								id:e._id,
								detail:'删除商品，商品名称：【'+e.name+'】，库存量：【'+e.kucunliang+'】',
								riqi: getDateTime.dateTimeStr('y-m-d h:i:s'),
								jingshouren:this.jingshouren,
								xiaoqu:e.xiaoqu
							}
						}).then(res=>{
							uni.hideLoading()
							this.shangpinlistfun()
						})
					},
					fail: () => {},
					complete: () => {}
				});
			},
			// 校区的数据库调取
			async xiaoqufun(){
				const res=await uni.getStorageSync('aoyashengxiaoqu')
				this.xiaoqu=[]
				let arr=[]
				for(var i=0;i<res.result.data.length;i++){
					var cou=0
					for(var j=i+1;j<res.result.data.length;j++){
						if(res.result.data[i].name==res.result.data[j].name){
							cou=9
							break
						}
					}
					if(cou==0){
						this.xiaoqu.push(res.result.data[i])
						arr.push(res.result.data[i].name)
					}
				}
				this.wodexiaoqu=arr
				
				this.shu1=this.wodexiaoqu
				if(this.xiaoqu.length>1){
					this.xiaoqu.unshift ({
						name:'全部'
					})
					this.shu11=this.xiaoqu[0].name//给校区填加商品时用
					this.shangpinlistfun()
				}else{
					this.shu3=this.xiaoqu[0].name
				}	
				},
			change(e){
				this.shu1=[]
				if(e.name=='全部'){
					this.shu1=this.wodexiaoqu
				}else{
					this.shu1.push(e.name)
				}
				this.shu11=e.name
				this.shangpinlistfun()
			},
			//卖货弹窗
			xiaoshou_show(e){
				this.show2=true
				this.shu7=e.jiage
				this.shu10=e.name
				this.shu14=e.xiaoqu
				this.shu15=e._id
				this.shu16=e.kucunliang
			},
			//卖货确认，一、maihuomingxi添加一条数据，二、zhangwuliushui添加一条数据，三、xiugaishuju添加一条数据
			xiaoshou(){
				uni.showLoading({
					title: '加载中…',
					mask: true
				});
				if(!this.shu9 || !this.shu7 || !this.shu6) {
					uni.showToast({
						title: '请输入各项信息！',
						icon: 'none',
						duration: 1000
					})
					uni.hideLoading()
					return
				}
				if(parseInt(this.shu16)<parseInt(this.shu6)){
					uni.showToast({
						title: '库存量为'+this.shu16+'，数量不足，不能销售！',
						icon: 'none',
						duration: 1000
					})
					uni.hideLoading()
					return
				}
				let item={}
				item.goumairen=this.shu9
				item.goumairiqi= new Date()
				item.jiage=parseFloat(this.shu7) 
				item.beizhu=this.shu8
				item.goumaishuliang=parseInt(this.shu6)
				item.shangpinname=this.shu10
				item.xiaoshouren=this.jingshouren
				item.xiaoqu=this.shu14
				uniCloud.callFunction({
					name:"funshare",
					data:{
						leixing:16,//类型为16时，新增卖货明细
						mingxi:item,
						jine:parseFloat(this.shu7) * parseFloat(this.shu6),
						biandong:"收入",
						leibie:"销售商品",
						detail:"销售给【"+this.shu9+"】" +this.shu10+"【数量：" +this.shu6+"】",
						riqi: getDateTime.dateTimeStr('y-m-d h:i:s'),
						jingshouren:this.jingshouren,
						xiaoqu:this.shu14
					}
				}).then(res=>{
					uni.showToast({
						title: '销售成功！',		
						icon: 'none',
						mask: true,
						duration: 1000
					})
					this.show2=false
					this.maihuomingxifun()
					uni.hideLoading()
				})
				//修改卖货后的库存量
				uniCloud.callFunction({
					name:"funshare",
					data:{
						leixing:17,//类型为17时，修改卖货后的库存量
						kucunliang:parseFloat(this.shu16)-parseFloat(this.shu6),
						_id:this.shu15
					}
				}).then(res=>{
					this.shangpinlistfun()
					// this.$refs.shangpin.refresh()
					
				})
			},
			//添加新商品，一、shangpin中添加一条数据，二、xiugaishuju中添加一条数据
			xinshangpin(){
				uni.showLoading({
					title: '商品添加…',
					mask: true
				});
				if(!this.shu11 ||this.shu11=='全部'){
					uni.showToast({
						title: '请选择正确的校区！',
						icon: 'none',
						duration: 1000
					})
					uni.hideLoading()
					return
				}
				if(!this.shu17 || !this.shu2 || !this.shu3 || !this.shu4 || !this.shu5) {
					uni.showToast({
						title: '请输入各项信息！',
						icon: 'none',
						duration: 1000
					})
					uni.hideLoading()
					return
				}
				uniCloud.callFunction({
					name:"funshare",
					data:{
						leixing:31,//类型为17时，修改卖货后的库存量/
						name:this.shu17,
						jieshao:this.shu2,
						zhaopian:this.shu5,
						kucunliang:this.shu3,
						jiage:this.shu4,
						yimaishuliang:0,
						xiaoqu:this.shu11,
						jingshouren:this.jingshouren,
						detail:'添加商品，商品名称：【'+this.shu7+'】，库存量：【'+this.shu3+'】，价格：【'+this.shu4+'】，介绍：【'+this.shu2+'】',
						riqi:getDateTime.dateTimeStr('y-m-d h:i:s'),
						
					}
				}).then(res=>{
					 toastTitle: '新增成功', // toast提示语
					 uni.hideLoading()
					 this.show1=false
					 this.shangpinlistfun()
				})
				
			},
			// 上传成功
			fanhuiurl(e){
				console.log("12ee",e.tempFiles[0].fileID)
				this.shu5=e.tempFiles[0].fileID
			},
			xinshangpin_show(){
				if(this.shu11=='全部'){
					uni.showToast({
						title: '请选择校区！',
						icon: 'none',
						duration: 1000
					})
					return
				}
				this.show1=true
				this.shu17=this.shu2=this.shu3=this.shu4=this.shu5=''
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-wrap {
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 200rpx;
		height: 100%;
	}

	.u-tab-item {
		height: 110rpx;
		background: #f6f6f6;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		font-weight: 400;
		line-height: 1;
	}

	.u-tab-item-active {
		position: relative;
		color: #000;
		font-size: 30rpx;
		font-weight: 600;
		background: #fff;
	}

	.u-tab-item-active::before {
		content: "";
		position: absolute;
		// border-left: 4px solid $u-type-primary;
		height: 32rpx;
		left: 0;
		top: 39rpx;
	}

	.u-tab-view {
		height: 100%;
	}

	.right-box {
		background-color: rgb(250, 250, 250);
	}

	.page-view {
		padding: 16rpx;
	}

	.class-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.class-item:last-child {
		min-height: 100vh;
	}

	.item-title {
		font-size: 26rpx;
		color: $u-main-color;
		font-weight: bold;
	}

	.item-menu-name {
		font-weight: normal;
		font-size: 28rpx;
		color: $u-main-color;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;
	}

	.thumb-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		// flex-direction: column;
		margin-top: 20rpx;;
	}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 15rpx;
	}
</style>
